KindEditor.lang({
  'uploadfile': '添加附件',
  'uploadfile.url': 'URL',
  'uploadfile.desc': '文件说明',
  'uploadfile.upload': '上传'
});
KindEditor.plugin('uploadfile', function (K) {
  var self = this,
    name = 'uploadfile'
  var uploadFileUrl = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php')
  var extraParams = K.undef(self.extraFileUploadParams, {})
  var filePostName = K.undef(self.filePostName, 'file')
  var staticHost = K.undef(self.staticHost, null)
  lang = self.lang(name + '.');
  self.plugin.uploadfileDialog = function (options) {
    var fileUrl = K.undef(options.fileUrl, 'http://'),
      fileTitle = K.undef(options.fileTitle, ''),
      clickFn = options.clickFn;
    var html = [
      '<div style="padding:20px;">',
      '<div class="ke-dialog-row">',
      '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
      '<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> &nbsp;',
      '<input type="button" id="imp-upload-btn" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
      '<input type="file" id="filecontainer" name="file" style="visibility:hidden"/>',
      '</div>',
      //title
      '<div class="ke-dialog-row">',
      '<label for="keTitle" style="width:60px;">' + lang.desc + '</label>',
      '<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>',
      '</div>',
      //form end
      '</form>',
      '</div>'
    ].join('');
    var dialog = self.createDialog({
      name: name,
      width: 450,
      title: self.lang(name),
      body: html,
      yesBtn: {
        name: self.lang('yes'),
        click: function (e) {
          var url = K.trim(urlBox.val()),
            title = titleBox.val();
          if (url == 'http://' || K.invalidUrl(url)) {
            alert(self.lang('invalidUrl'));
            urlBox[0].focus();
            return;
          }
          if (K.trim(title) === '') {
            title = url;
          }
          var fileObj = filecontainer.files[0]; // 获取文件对象
          var FileController = uploadFileUrl; // 接收上传文件的后台地址 
          //   console.log(uploadimgUrl)
          // FormData 对象
          var form = new FormData();
          for (var key in extraParams) {
            form.append(key, extraParams[key])
          }
          form.append(filePostName, fileObj); // 文件对象
          // XMLHttpRequest 对象
          var xhr = new XMLHttpRequest();
          xhr.open("post", FileController, true);
          xhr.onreadystatechange = function (response) {
            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
              var data = JSON.parse(xhr.response);
              if (data.error === 0) {
                var url = data.url;
                urlBox.val(url)
                if (dialog.isLoading) {
                  return;
                }
                // insert remote image
                clickFn.call(self, url, title);
              } else {
                alert(data.message);
              }
            }
          }
          //   xhr.onload = function (response) {
          //     console.log(response)
          //     alert("上传完成!");
          //   };
          xhr.send(form);

        }
      }
    })

    var div = dialog.div;
    var urlBox = K('[name="url"]', div),
      titleBox = K('[name="title"]', div);
    var textcontainer = document.getElementById('keUrl')
    var filecontainer = document.getElementById('filecontainer')
    filecontainer.addEventListener('change', function (e) {
      // console.log(textcontainer)
      textcontainer.value = filecontainer.value
    })
    document.getElementById('imp-upload-btn').addEventListener('click', function (e) {
      filecontainer.click()
    })
  };
  self.clickToolbar(name, function () {
    self.plugin.uploadfileDialog({
      clickFn: function (url, title) {
        url = staticHost + url
        var html = '<a class="ke-insertfile" href="' + url + '" data-ke-src="' + url + '"  download>' + title + '</a>';
        self.insertHtml(html).hideDialog().focus();
      }
    });
  });
});
